﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Win32;
using eStock.Common;
using eStock.DataObjects;

namespace eStock.ChildWindows
{
    /// <summary>
    /// Interaktionslogik für WndAddEditComponent.xaml
    /// </summary>
    public partial class WndAddEditComponent
    {
        private readonly bool _edit = false;
        private readonly int _cId;

        private string _imgName;

        public WndAddEditComponent()
        {
            InitializeComponent();
            Loaded += WndAddEditComponentLoaded;
        }

        void WndAddEditComponentLoaded(object sender, RoutedEventArgs e)
        {
            foreach (ComponentType type in DatabaseObjects.Types)
            {
                ComboBoxItem item = new ComboBoxItem {Content = type.Title, Tag = type.Id};
                cbCategory.Items.Add(item);
            }
            
        }

        public WndAddEditComponent(int id)
        {
            InitializeComponent();
            Loaded += WndAddEditComponentLoaded;
            InserValues(id);
            _edit = true;
            _cId = id;
        }
        private void BtnAbbortClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void InserValues(int id)
        {
            Component c = DatabaseObjects.Components.GetById(id);

            if (c == null) return;
            txtTitle.Text = c.Title;
            txtDescription.Text = c.Description;
            if(c.Image != null)
            {
                imgPreview.Source = c.Image.Image.Source;
                _imgName = c.Image.Title;
            }
            cbCategory.SelectedIndex = cbCategory.GetIndexByTag(c.TypeId);
        }



        private void BtnSaveClick(object sender, RoutedEventArgs e)
        {
            busyIndi.IsBusy = true;
            bool state = true;
            Threading.RunAsThread((id, obj) =>
                                      {
                                          string stxtTitle = string.Empty, stxtFilePath = string.Empty, stxtImgTitle = string.Empty,
                                              stxtDescription = string.Empty;
                                          int? iType = null;                                          
                                          Dispatcher.Invoke(new Action(() =>
                                                                           {
                                                                               stxtTitle = txtTitle.Text;
                                                                               stxtFilePath = txtFilePath.Text;
                                                                               stxtImgTitle = _imgName;
                                                                               stxtDescription = txtDescription.Text;

                                                                               if (cbCategory.SelectedItem != null) iType = (int)((ComboBoxItem)cbCategory.SelectedItem).Tag;
                                                                           }));
                                          
                                                                                    if (string.IsNullOrWhiteSpace(stxtTitle))
                                                                                    {
                                                                                       Dispatcher.Invoke(new Func<MessageBoxResult>(() => MessageBox.Show(
                                                                                           "Sie müssen einen Titel angeben.",
                                                                                           "Fehler beim Hinzufügen",
                                                                                           MessageBoxButton.OK,
                                                                                           MessageBoxImage.Warning)));
                                                                                        state = false;
                                                                                        return;
                                                                                    }


                                          try
                                              {
                                                  //Load Image and insert into / update SQLDatabase
                                                  DBImage img = null;
                                                  if (!string.IsNullOrWhiteSpace(stxtImgTitle))
                                                  {

                                                      img = !_edit ? new DBImage() : DatabaseObjects.Components.GetById(_cId).Image;
                                                      if (img != null)
                                                      {
                                                          img.Title = stxtImgTitle;
                                                          img.ImgType = stxtFilePath.Substring(stxtFilePath.LastIndexOf(".", StringComparison.Ordinal) + 1, (stxtFilePath.Length - 1) - (stxtFilePath.LastIndexOf(".", StringComparison.Ordinal)));
                                                          Dispatcher.Invoke(new Func<Image>(() => img.Image = new Image { Source = imgPreview.Source }));
                                                      }
                                                      if(!_edit)
                                                          DatabaseObjects.Images.Add(img);
                                                      else if (img != null)
                                                              DatabaseObjects.Images.Replace(img);
                                                      
                                                      if (!DatabaseObjects.Images.Update(Dispatcher))
                                                      {
                                                            ErrorHandler.ThrowError(new Exception("Fehler beim updaten der Datenbank!",MainWindow.Database.LastError),"");
                                                      }
                                                  }

                                                  //Load Component and insert into SQLDatabase
                                                  Component c = !_edit ? new Component() : DatabaseObjects.Components.GetById(_cId);
                                                  c.Title = stxtTitle;
                                                  c.Description = stxtDescription;
                                                  if (img != null)
                                                      c.ImgId = img.Id;
                                                  if (iType != null)
                                                      c.TypeId = iType.Value;

                                                  if(!_edit)
                                                    DatabaseObjects.Components.Add(c);
                                                  else
                                                      DatabaseObjects.Components.Replace(c);
                                                  if (!DatabaseObjects.Components.Update())
                                                  {
                                                      ErrorHandler.ThrowError(new Exception("Fehler beim updaten der Datenbank!",MainWindow.Database.LastError),"");
                                                  }


                                                  // Now update the UI
                                                  try
                                                  {
                                                      Dispatcher.Invoke(new Action(() => ((MainWindow)Application.Current.MainWindow).UpdateUI()));
                                                  }
                                                  catch (Exception x)
                                                  {
                                                      Logging.WriteError("Failed to upload UserInterface after adding new Item: " +x.Message);
                                                  }
                                              }
                                              catch (Exception x)
                                              {
                                                  ErrorHandler.ThrowError(new Exception("Es ist ein Fehler beim hinzufügen des Bauteils aufgetreten!",x),"",false);
                                              }
                                      });
            Threading.WaitForThreadsAsnc(() => { }, () => Dispatcher.Invoke(new Action(() =>{busyIndi.IsBusy = false;if(state)Close();})));
        }

        private void BtnBrowseClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog
                                     {
                                         Filter = "Bilddateien (*.jpg,*.jpeg,*.gif,*.bmp,*.png,*.ico)|*.jpg;*.jpeg;*.gif;*.bmp;*.png;*ico",
                                         Multiselect = false
                                     };

            bool? result = dlg.ShowDialog();
            if (result == true)
            {
                txtFilePath.Text = dlg.FileName;
            }
        }

        private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (busyIndi.IsBusy)
            {
                e.Cancel = true;
            }
        }


        private void ImgPreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            cldNewImage.Show();
        }

        private void BtnOkNewImageClick(object sender, RoutedEventArgs e)
        {
            if(string.IsNullOrEmpty(txtFilePath.Text))
            {
                ErrorHandler.ThrowError(new Exception("Bitte wählen Sie zuerst eine Datei"),"Keine Datei ausgewählt.",false );
                return;
            }
            try
            {
                imgPreview.Source = Functions.OpenImageFromFile(txtFilePath.Text);
                _imgName = Path.GetFileNameWithoutExtension(txtFilePath.Text);
                cldNewImage.Close();
            }
            catch (Exception)
            {
                Logging.WriteError("Failed to set preview image while adding new Item");
                ErrorHandler.ThrowError(new Exception("Fehler beim Laden der Datei. Möglicherweise ist die Datei ungültig."), "", false);
            }
        }

        private void BtnAbbortNewImageClick(object sender, RoutedEventArgs e)
        {
            txtFilePath.Text = string.Empty;
            cldNewImage.Close();
        }
    }
}
